import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FetchService } from '../../../core/net/fetch.service';
import { UtilService } from '../../../core/util/util.service';
import { Router } from '@angular/router';
import { DispatchPlanService } from '../dispatch-plan.service';
import * as moment from 'moment';
import { differenceInCalendarDays } from 'date-fns';

@Component({
  selector: 'app-sub-year-plan',
  templateUrl: './sub-year-plan.component.html',
  styleUrls: ['./sub-year-plan.component.scss']
})
export class SubYearPlanComponent implements OnInit, AfterViewInit {
    tableData = [];
    year = "";    // 默认查后一年年
    tableHeight = "400px";
    scrollConfig =  {
        y: '400px'
    };
    pageNum = 1;
    pageSize = 10;
    total: number;
    loading = true;
    sectionId = JSON.parse(localStorage.userInfo).sectionId;
    @ViewChild('wrap') elementView: ElementRef;
    constructor(
        private fetchService: FetchService,
        private util: UtilService,
        private router: Router,
        private dispatchService: DispatchPlanService,
    ) {
    }

    ngOnInit() {
        this.getGridData();
    }
    ngAfterViewInit() {
        this.scrollConfig.y = (this.elementView.nativeElement.offsetHeight - 160) + 'px';
    }
    getGridData(): void {
        const params = {
            sectionId: this.sectionId === '1' ? '' : this.sectionId,
            y: moment(this.year).year() || "",
        };
        this.fetchService.post<any>('sys/yjqYearPlan/queryList', params).subscribe(res => {
            this.loading = false;
            if (res && Array.isArray(res)) {
                this.total = res.length;
                this.tableData = res;
            } else {
                this.total = 0;
                this.tableData = [];
            }
        });
    }

    disabledDate = (current: Date): boolean => {
        // 不能选明年之后的日期
        return differenceInCalendarDays(current, moment().add(1, 'y').valueOf()) > 0;
    }

    openDetailPage(type, name?, sectionId?, year?): void {
        this.router.navigate(['/dispatch-plan/sub-year-plan-add'], { skipLocationChange: true, queryParams: {type: type, name: name, year: year, sectionId: sectionId}});
    }

    reset(): void {
        this.year = null;
        this.getGridData();
    }
}
